{% extends "base.html" %}
{% load static %}

{% block title %}工作流模板管理{% endblock %}

{% block extra_css %}
<link href="{% static 'css/workflow.css' %}" rel="stylesheet">
<style>
.template-card {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    background: white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.template-stats {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
}

.stat-item {
    text-align: center;
    flex: 1;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #007bff;
}

.stat-label {
    font-size: 12px;
    color: #6c757d;
    margin-top: 5px;
}

.version-badge {
    background: #e9ecef;
    color: #495057;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
}

.performance-indicator {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 5px;
}

.performance-good { background-color: #28a745; }
.performance-warning { background-color: #ffc107; }
.performance-danger { background-color: #dc3545; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-cogs"></i> 工作流模板管理</h2>
                <div>
                    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#importModal">
                        <i class="fas fa-upload"></i> 导入模板
                    </button>
                    <a href="{% url 'assets:workflow_designer' %}" class="btn btn-primary">
                        <i class="fas fa-plus"></i> 创建模板
                    </a>
                </div>
            </div>

            <!-- 筛选和搜索 -->
            <div class="card mb-4">
                <div class="card-body">
                    <form method="get" class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">模板类型</label>
                            <select name="template_type" class="form-select">
                                <option value="">全部类型</option>
                                {% for choice in template_types %}
                                <option value="{{ choice.0 }}" {% if current_filters.template_type == choice.0 %}selected{% endif %}>
                                    {{ choice.1 }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">状态</label>
                            <select name="status" class="form-select">
                                <option value="">全部状态</option>
                                <option value="active" {% if current_filters.status == 'active' %}selected{% endif %}>启用</option>
                                <option value="inactive" {% if current_filters.status == 'inactive' %}selected{% endif %}>停用</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">搜索</label>
                            <input type="text" name="search" class="form-control" 
                                   placeholder="搜索模板名称或描述" value="{{ current_filters.search }}">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <div>
                                <button type="submit" class="btn btn-outline-primary">
                                    <i class="fas fa-search"></i> 搜索
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>          
  <!-- 模板列表 -->
            <div class="row">
                {% for template in templates %}
                <div class="col-lg-6 col-xl-4">
                    <div class="template-card">
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <div>
                                <h5 class="mb-1">{{ template.name }}</h5>
                                <span class="version-badge">v{{ template.version }}</span>
                                {% if template.is_optimized %}
                                <span class="badge bg-info ms-1">优化版</span>
                                {% endif %}
                            </div>
                            <div class="dropdown">
                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" 
                                        data-bs-toggle="dropdown">
                                    <i class="fas fa-ellipsis-v"></i>
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" href="{% url 'assets:workflow_designer' %}?template_id={{ template.id }}">
                                        <i class="fas fa-edit"></i> 编辑
                                    </a></li>
                                    <li><a class="dropdown-item" href="#" onclick="cloneTemplate({{ template.id }})">
                                        <i class="fas fa-copy"></i> 克隆
                                    </a></li>
                                    <li><a class="dropdown-item" href="#" onclick="exportTemplate({{ template.id }})">
                                        <i class="fas fa-download"></i> 导出
                                    </a></li>
                                    <li><a class="dropdown-item" href="#" onclick="viewAnalytics({{ template.id }})">
                                        <i class="fas fa-chart-bar"></i> 分析
                                    </a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item text-danger" href="#" onclick="deleteTemplate({{ template.id }})">
                                        <i class="fas fa-trash"></i> 删除
                                    </a></li>
                                </ul>
                            </div>
                        </div>

                        <p class="text-muted small mb-3">{{ template.description|truncatechars:100 }}</p>

                        <div class="mb-3">
                            <span class="badge bg-secondary">{{ template.get_template_type_display }}</span>
                            {% if template.is_active %}
                            <span class="badge bg-success">启用</span>
                            {% else %}
                            <span class="badge bg-secondary">停用</span>
                            {% endif %}
                        </div>

                        <!-- 性能指标 -->
                        <div class="mb-3">
                            <small class="text-muted">性能指标:</small><br>
                            <span class="performance-indicator performance-{{ template.performance_level }}"></span>
                            <small>完成率: {{ template.completion_rate|floatformat:1 }}%</small>
                            <span class="ms-2">
                                <small>平均时长: {{ template.avg_duration|floatformat:1 }}h</small>
                            </span>
                        </div>

                        <!-- 统计数据 -->
                        <div class="template-stats">
                            <div class="stat-item">
                                <div class="stat-value">{{ template.total_instances }}</div>
                                <div class="stat-label">总实例</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value">{{ template.active_instances }}</div>
                                <div class="stat-label">运行中</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value">{{ template.step_count }}</div>
                                <div class="stat-label">步骤数</div>
                            </div>
                        </div>

                        <div class="mt-3 pt-3 border-top">
                            <small class="text-muted">
                                创建: {{ template.created_at|date:"Y-m-d" }} by {{ template.created_by.username }}
                            </small>
                        </div>
                    </div>
                </div>
                {% empty %}
                <div class="col-12">
                    <div class="text-center py-5">
                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">暂无工作流模板</h5>
                        <p class="text-muted">点击"创建模板"开始设计您的第一个工作流</p>
                        <a href="{% url 'assets:workflow_designer' %}" class="btn btn-primary">
                            <i class="fas fa-plus"></i> 创建模板
                        </a>
                    </div>
                </div>
                {% endfor %}
            </div>

            <!-- 分页 -->
            {% if page_obj.has_other_pages %}
            <nav aria-label="模板分页">
                <ul class="pagination justify-content-center">
                    {% if page_obj.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if request.GET.template_type %}&template_type={{ request.GET.template_type }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.search %}&search={{ request.GET.search }}{% endif %}">
                            上一页
                        </a>
                    </li>
                    {% endif %}

                    {% for num in page_obj.paginator.page_range %}
                    {% if page_obj.number == num %}
                    <li class="page-item active">
                        <span class="page-link">{{ num }}</span>
                    </li>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ num }}{% if request.GET.template_type %}&template_type={{ request.GET.template_type }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.search %}&search={{ request.GET.search }}{% endif %}">
                            {{ num }}
                        </a>
                    </li>
                    {% endif %}
                    {% endfor %}

                    {% if page_obj.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if request.GET.template_type %}&template_type={{ request.GET.template_type }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.search %}&search={{ request.GET.search }}{% endif %}">
                            下一页
                        </a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
            {% endif %}
        </div>
    </div>
</div>

<!-- 导入模板模态框 -->
<div class="modal fade" id="importModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">导入工作流模板</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="importForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">选择模板文件</label>
                        <input type="file" class="form-control" name="file" accept=".json" required>
                        <div class="form-text">支持JSON格式的模板文件</div>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        导入的模板将自动验证，确保工作流定义的正确性。
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-upload"></i> 导入
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 模板分析模态框 -->
<div class="modal fade" id="analyticsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">模板使用分析</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="analyticsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 克隆模板
function cloneTemplate(templateId) {
    if (confirm('确定要克隆这个模板吗？')) {
        fetch(`/assets/workflow/templates/${templateId}/clone/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', '模板克隆成功');
                setTimeout(() => {
                    window.location.href = `/assets/workflow/designer/?template_id=${data.template_id}`;
                }, 1000);
            } else {
                showAlert('danger', data.message || '克隆失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('danger', '克隆失败');
        });
    }
}

// 导出模板
function exportTemplate(templateId) {
    window.location.href = `/assets/workflow/templates/${templateId}/export/`;
}

// 查看分析
function viewAnalytics(templateId) {
    const modal = new bootstrap.Modal(document.getElementById('analyticsModal'));
    modal.show();
    
    // 加载分析数据
    fetch(`/assets/workflow/templates/${templateId}/analytics/`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('analyticsContent').innerHTML = renderAnalytics(data);
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('analyticsContent').innerHTML = 
                '<div class="alert alert-danger">加载分析数据失败</div>';
        });
}

// 渲染分析数据
function renderAnalytics(data) {
    return `
        <div class="row">
            <div class="col-md-6">
                <h6>基础统计</h6>
                <ul class="list-unstyled">
                    <li>总实例数: <strong>${data.usage_stats.total_instances}</strong></li>
                    <li>完成率: <strong>${data.performance_stats.completion_rate?.toFixed(1) || 0}%</strong></li>
                    <li>平均处理时间: <strong>${(data.performance_stats.avg_duration / 3600)?.toFixed(1) || 0} 小时</strong></li>
                </ul>
            </div>
            <div class="col-md-6">
                <h6>状态分布</h6>
                <ul class="list-unstyled">
                    ${Object.entries(data.usage_stats.status_distribution).map(([status, info]) => 
                        `<li>${status}: <strong>${info.count}</strong> (${info.percentage.toFixed(1)}%)</li>`
                    ).join('')}
                </ul>
            </div>
        </div>
        ${data.recommendations.length > 0 ? `
        <div class="mt-4">
            <h6>优化建议</h6>
            ${data.recommendations.map(rec => `
                <div class="alert alert-${rec.priority === 'high' ? 'warning' : 'info'} alert-sm">
                    <strong>${rec.title}</strong><br>
                    ${rec.description}<br>
                    <small class="text-muted">${rec.suggestion}</small>
                </div>
            `).join('')}
        </div>
        ` : ''}
    `;
}

// 删除模板
function deleteTemplate(templateId) {
    if (confirm('确定要删除这个模板吗？此操作不可恢复！')) {
        fetch(`/assets/workflow/templates/${templateId}/delete/`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', '模板删除成功');
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert('danger', data.message || '删除失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('danger', '删除失败');
        });
    }
}

// 导入表单提交
document.getElementById('importForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('/assets/workflow/templates/import/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', '模板导入成功');
            bootstrap.Modal.getInstance(document.getElementById('importModal')).hide();
            setTimeout(() => location.reload(), 1000);
        } else {
            showAlert('danger', data.message || '导入失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', '导入失败');
    });
});

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    const container = document.querySelector('.container-fluid');
    container.insertBefore(alertDiv, container.firstChild);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}
</script>
{% endblock %}